<template>
  <div>
    <el-upload
      class="upload-demo"
      drag
      :action="baseUrl + uploadUrl"
      :limit="limit"
      :data="theData"
      :file-list="theFileList"
      :auto-upload="autoUpload"
      :accept="accept"
      :headers="headers"
      :before-upload="beforeUpload"
      :on-success="uploadSuccess"
      :on-error="uploadError"
    >
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">
        将文件拖到此处，或<em>点击上传</em>
      </div>
      <div class="el-upload__tip" slot="tip">只能上传{{accept}}文件，且不超过{{maxSize}}MB</div>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/token'
import * as auth from '@/utils/auth'
import { uuid } from '@/utils/utils'
const baseUrl = process.env.VUE_APP_BASE_API

export default {
  name: 'UploadFile',
  props: {
    action: {
      type: String,
      default: ''
    },
    limit: {
      tpye: Number,
      default: 1
    },
    fileList: {
      type: Array,
      default: () => []
    },
    autoUpload: {
      type: Boolean,
      default: true
    },
    accept: {
      type: String,
      default: '.jpg,.jpeg,.png,.gif,.bmp'
    },
    data: {
      type: Object,
      dfeault: {}
    },
    maxSize: {
      type: Number,
      default: 5
    },
    formProp: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      baseUrl: baseUrl,
      imageUrl: null,
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      theFileList: this.fileList,
      uploadUrl: this.action,
      theData: this.data
    }
  },
  computed: {},
  mounted() {
    this.setHeaders()
  },
  methods: {
    beforeUpload(file) {
      const filename = file.name
      const filesize = file.size
      const ext = filename.substring(filename.lastIndexOf('.'))
      if (this.accept.indexOf(ext) < 0) {
        this.$message.error('请上传' + this.accept + '格式的文件')
        return false
      }
      if (filesize > this.maxSize * 1024 * 1024) {
        this.$message.error('文件最大大小' + this.maxSize + 'MB')
        return false
      }
    },
    uploadSuccess(res, file, fileList) {
      this.$message.success('上传成功')
      if (this.formProp) {
        this.$emit('fileUploadSuccess', this.formProp, res.data)
      }
    },
    uploadError(error, file, fileList) {
      this.$message.error('上传失败' + error)
    },
    setHeaders() {
      this.headers['App-Auth-appid'] = auth.APPID
      if (auth.APP_AUTH_ENABLE) {
        this.headers['App-Auth-reqUrl'] = this.uploadUrl
        let timestamp = new Date().getTime()
        let nonceStr = uuid()
        this.headers['App-Auth-timestamp'] = timestamp
        this.headers['App-Auth-nonceStr'] = nonceStr
        this.headers['App-Auth-sign'] = auth.generateSignQs(
          this.uploadUrl,
          timestamp,
          nonceStr,
          {}
        )
      }
    }
  }
}
</script>

<style lang="scss">
</style>
